import {Component, ViewEncapsulation, ViewChild, Input} from '@angular/core';
import {IdeaService} from '../../services/app.idea';
import {UserService} from '../../services/app.user';
//import './postIdea.loader.ts';
import {Router} from '@angular/router';
import {BaThemeSpinner} from '../../theme/services';
import {CKEditorComponent} from 'ng2-ckeditor';
import {Modal} from 'ngx-modal';
import {Utility} from '../../services/app.utility';
import {Constants} from '../../../app/common/app.constants';
import {TagModel} from 'ngx-chips/core/accessor';
import {Observable} from 'rxjs';
import {FormControl} from '@angular/forms';
import {current} from 'codelyzer/util/syntaxKind';
import {Ideas} from '../shared/ideas/idea.component';

declare let toastr: any;
declare let $: any;
declare let Treant: any;
declare let CKEDITOR: any;


@Component({
    selector: 'postIdea-component',
    encapsulation: ViewEncapsulation.None,
    templateUrl: './postIdea.html',
    styleUrls: ['./postIdea.scss']
})

export class PostIdea {

    @ViewChild('ideas')
    public idea: Ideas;

    @Input()
    constants: Constants;
    public validEmailPattern = /.*\S.*/;
    @ViewChild('citationTree')
    private citationTreeModal: Modal;

    @ViewChild('keywordModal')
    private keywordModal: Modal;

    @ViewChild('ckEditor')
    private ckEditor: CKEditorComponent;
    public items: any;
    public tags: any = [];
    public citationArray1: any = [];
    public maxTag: Boolean;
    public citation: any = {};
    public versioning: boolean;
    public canSuggest: boolean;
    public keyWordShow: any;
    public keyWordHidden: any;
    public userVersion: any;
    public sentenceSuggestShow: boolean;
    public showIdeaButton: boolean;
    public showSuggest: boolean;
    public descriptionShow: boolean;
    public sentenceContent: any;
    public checkSubmit: boolean;
    public isSuggesting: boolean; // 是否正在进行匹配
    public isSuccessful: boolean; // 是否正在进行匹配
    public isNeed: boolean; // 是否正在进行匹配
    public processing: boolean; // 是否正在进行匹配
    public postTitle: string = null;
    public postDescription: string = null;
    public postTag: any;
    public checkCount: any;
    public showIdeaPage: any;
    public cloudContentSuggestion: any;
    public constContentSuggestion: any;
    public cloudContentSuggestionWords: any;
    public submitPostDisable: boolean;
    public postButton: any;
    public submitButton: any;
    public mySnippets: any = null;
    public myKeyWordList: any = null;
    public myKeyWordTip: any = null;
    public ideaShowList: any = null;
    public ckeditorContent: any;
    public checkAutoSave: boolean;
    public autoScrollFilter: boolean;
    public titleClick: boolean;
    public showIdeaTopWindow: boolean;

    public config = {
        uiColor: '#F0F3F4',
    };
    public myDatePickerOptions: any;
    public previousContent: string;
    public queryKeywordList: any = [];
    public start: any;
    public end: any;
    public check: any;
    public allTags: any;

    public autoCompleteList: any = [];
    public autoKeywordList: any = [];
    public autoCompleteIdeasList: any = [];
    public constContentSuggestionWords: any = [];
    public currentIndex: any;
    public currentIdeasIndex: any;
    public pageButtonShow: boolean;
    public pageIdeasButtonShow: boolean;
    public pageId: any;
    public currentClickKeyword: any;
    public currentClickKeywordCount: any;
    public currentClickKeywordTip: any;

    public isFirstLoad: boolean;


    private that: any;

    is_content_added = false;
    optionstags: any = {
        placeholder: 'Search by Tags',
        secondaryPlaceholder: 'Search by Tags',
    };
    ckeConfig: any;

    constructor(private IdeaService: IdeaService, private userService: UserService, private router: Router, private spinner: BaThemeSpinner, private utility: Utility) {


        this.constants = new Constants();
        this.spinner.hideProgress();
        this.maxTag = false;
        this.versioning = false;
        this.submitPostDisable = true;
        // this.canSuggest = true;
        this.previousContent = '';
        this.cloudContentSuggestion = [];
        this.cloudContentSuggestionWords = [];
        this.autoKeywordList = [];
        this.citationArray1 = [];
        this.tags = false;
        this.postButton = true;
        this.processing = false;
        this.checkSubmit = false;
        this.checkCount = 0;
        this.showIdeaPage = 1;
        this.start = 0;
        this.check = 0;
        this.checkAutoSave = false;
        this.sentenceSuggestShow = false;
        this.showSuggest = true;
        this.autoScrollFilter = true;
        this.titleClick = false;
        this.isNeed = true;
        this.currentIndex = 0;
        this.currentIdeasIndex = 1;
        this.pageButtonShow = true;
        this.pageIdeasButtonShow = true;
        this.isFirstLoad = true;
        this.constContentSuggestion = [];
        this.ideaShowList = [];
        this.showIdeaButton = true;
        this.currentClickKeywordTip = "点击关键字查看频次信息"

        // function for get save tags
        const that = this;
        setTimeout(function () {
            that.getTags();
        }, 3000);


        // function for start timeline count
        this.startCount();

        toastr.options = {positionClass: 'toast-top-right'};
        this.myDatePickerOptions = {
            todayBtnTxt: 'Today',
            dateFormat: 'yyyy-mm-dd',
            firstDayOfWeek: 'mo',
            sunHighlight: true,
            height: '34px',
            width: '260px',
            inline: false,
            disableUntil: {year: 2016, month: 8, day: 10},
            selectionTxtFontSize: '16px'
        };
        this.citation.count = '';
        this.citation.name = '';
        this.citation.date = '';
        // API for get user info
        this.userService.getuserInfo().subscribe(
            data => this.userInfoSuccess(data),
            error => this.userInfoFail(error)
        );


        // auto save after 1 min
        setTimeout(() => {
            this.savePostIdeaContent();
        }, 60000);


        // call every 2 min for save post an idea
        setInterval(() => {
            this.savePostIdeaContent();
        }, 120000);


    }

    ngOnInit() {
        this.ckeConfig = {
            allowedContent: true,
            height: 300
        };
    }

    ngDoCheck() {
        if (this.ckeditorContent && this.ckeditorContent.trim()) {
            this.is_content_added = true;
        } else {
            this.is_content_added = false;
        }
    }

    init() {
        this.cloudContentSuggestion = [];
        this.cloudContentSuggestionWords = [];
        this.autoCompleteList = [];
        this.autoKeywordList = [];
        this.autoCompleteIdeasList = [];
        this.constContentSuggestionWords = [];
        this.constContentSuggestion = [];
    }

    // defined cloud Content Suggestion Word
    ngAfterViewInit() {
        this.cloudContentSuggestionWords = [];
        this.getPostIdea();
        this.getIdeaShowByPage(1, 10);
        // this.getTop10Keyword();
        // this.getTopIdeas(this.currentIdeasIndex);
    }

    getTop10Keyword() {
        this.IdeaService.getTop10Keyword({}).subscribe(
            data => this.getTop10IdeaSucessfully(data),
            error => console.log());
    }

    getIdeaShowByPage(pageId, pageSize) {
        this.IdeaService.getIdeaShowByPage({
            pageId: pageId,
            pageSize: pageSize
        }).subscribe(
            data => this.getIdeaShowByPageSucessfully(data),
            error => console.log());
    }

    getTopIdeas(pageId) {
        this.IdeaService.getTopIdeas({pageId: pageId}).subscribe(
            data => this.getTopIdeasSucessfully(data),
            error => console.log());
    }

    getMoreIdeasByPage(pageId) {
        this.IdeaService.getTopIdeas({pageId: pageId}).subscribe(
            data => this.getMoreIdeasSucessfully(data),
            error => console.log());
    }

    getPostIdea() {
        this.IdeaService.getPostIdea({}).subscribe(
            data => this.getPostIdeaSucessfully(data),
            error => console.log());
    }

    showMoreModalIdeas() {
        this.getIdeaShowByPage(++this.showIdeaPage, 10);
    }

    showKeywordInfo(event, item) {
        var target = event.target.getAttribute('class');
        console.log(item);
        if ('idea-keyword' == target) {
            this.currentClickKeywordTip = '';
            this.currentClickKeyword = event.toElement.textContent;
            var currentIndex = item.keywords.indexOf(event.toElement.textContent);
            if (currentIndex != -1) {
                var temp = item.keywords_counts_ranking[currentIndex].split(",");
                this.currentClickKeywordTip = '(' + temp[0] + '  ;  ' + (parseFloat(temp[2])*100).toFixed(2) + '%)';
                this.currentClickKeywordCount = temp[0];
            }
            this.keywordModal.open();
        }
    }

    // Convert Date to MM/DD/YY
    public formateDate(dates): any {
        return this.utility.getFormattedDateForTree(dates);
    }

    // 计算keyword样式
    getKeywordClass(count) {

        count = count;

        if (count < 45) {
            if (count < 9) {
                return 'rare_5';
            } else if (count < 18) {
                return 'rare_4';
            } else if (count < 27) {
                return 'rare_3';
            } else if (count < 36) {
                return 'rare_2';
            } else {

                return 'rare_1';
            }
        } else {
            if (count < 56) {
                return 'hot_5';
            } else if (count < 67) {
                return 'hot_4';
            } else if (count < 78) {
                return 'hot_3';
            } else if (count < 89) {
                return 'hot_2';
            } else {

                return 'hot_1';
            }
        }


    }

    // 计算keyword样式
    getKeywordTip(count) {

        if (count < 45) {

            return 'rare';
        } else {

            return 'hot';
        }


    }

    // 计算keyword样式
    getKeywordSign(percent) {
        if (percent < 45) {
            return 'rare';
        } else {
            return 'hot';
        }
    }

    getTop10IdeaSucessfully(data) {
        console.log(data);
        this.constContentSuggestionWords = data.result;

        // 记录日志
        const tip = {
            'target': 'load const keywords',
            'value': this.currentIdeasIndex,
            'action': 'load const keywords',
            'context': data.result
        };
        this.setUserLogs(tip);

    }

    getIdeaShowByPageSucessfully(data) {
        var that = this;

        /*$.each(this.autoCompleteList, function (index, item) {

            // var temp = queryContent.trim().split(" ")
            var temp = result.keyWordList;
            temp.forEach(function (splitItem, index) {
                var reg = '/\\b' + splitItem + '\\b/gi';
                item.content = item.content.replace(eval(reg), '<span>' + splitItem + '</span>');
            });

        });*/


        data.forEach(function (singleItem, index) {

            var temp = singleItem.keywords;
            temp.forEach(function (splitItem, index) {
                var reg = '/\\b' + splitItem + '\\b/gi';
                singleItem.content = singleItem.content.replace(eval(reg), '<span class="idea-keyword">' + splitItem + '</span>');
            });

            that.ideaShowList.push(singleItem);
        });
    }

    getTopIdeasSucessfully(data) {
        this.constContentSuggestion = this.constContentSuggestion.concat(data);

        // 记录日志
        const tip = {
            'target': 'load more const ideas',
            'value': this.currentIdeasIndex,
            'action': 'load more const ideas',
            'context': data
        };
        this.setUserLogs(tip);
    }

    getMoreIdeasSucessfully(data) {
        var that = this;
        $.each(data, function (index, item) {
            that.cloudContentSuggestion.push({'content': item});
        });
        this.currentIdeasIndex = this.currentIdeasIndex + 1;
        // 记录日志
        const tip = {
            'target': 'load more const ideas',
            'value': this.currentIdeasIndex,
            'action': 'load more const ideas',
            'context': data
        };
        this.setUserLogs(tip);
    }

    getPostIdeaSucessfully(data) {

        if (data.savedIdea) {
            this.mySnippets = data.savedIdea.title;
            this.tags = data.savedIdea.tags;
            const ckValue = data.savedIdea.description;
            this.ckEditor.writeValue(ckValue);
            if (this.mySnippets) {
                this.submitPostDisable = false;
            }
        }
    }

    // function for get idea data fromAPI
    public getIdea(idea): void {
        idea = idea.trim();

        if (idea.length > 2) {
            this.submitPostDisable = false;
            const data = {
                title: idea
            };
            this.IdeaService.getIdea(data).subscribe(
                data => this.getIdeaPostedSucessfully(data),
                error => this.getIdeaPostedFail(error));
        } else {
            this.items = null;
        }
    }

    // function for get idea data success
    private getIdeaPostedSucessfully(data) {
        this.items = data;
    }

    // function for get idea data fail
    private getIdeaPostedFail(error) {
    }


    // Fuction call on click post idea button
    public onSubmit(title, description): void {
        this.spinner.showProgress();
        let content = description;
        this.submitButton = false;
        const tags_post = [];

        this.tags = this.tags || [];

        this.tags.map(item => tags_post.push(item.value));
        for (let i = 0; i < this.cloudContentSuggestionWords.length; i++) {
            // content = content.split(this.cloudContentSuggestionWords[i].split("(")[0]).join('<span class="keywordColor">' + this.cloudContentSuggestionWords[i].split("(")[0] + '</span>');
            this.citationArray1.push(this.cloudContentSuggestionWords[i].content);
        }
        // 去除高亮显示
        var test = '/color:#FF0000/gi';
        content = content.replace(eval(test), '');
        const data = {
            title: title,
            content: content,
            tags: tags_post.length ? tags_post : [],
            cloudContent: this.ckEditor.instance.editable().getText(),
            citation: {
                'showCou': this.citation.count,
                'name': this.citation.name,
                'updatedAt': this.citation.date
            },
            citationArray: this.citationArray1
        };
        this.IdeaService.userIdea(data).subscribe(
            data => this.IdeaPostedSucessfully(),
            error => this.IdeaPostedFail(error));
    }

    // Fuction call on post idea success
    private IdeaPostedSucessfully() {
        this.checkCount = 0;
        this.submitPostDisable = false;
        this.spinner.hideProgress();
        toastr.success(this.constants.IDEAPOSTEDSUCCESSFULLY);
        while (this.tags.length) {
            this.tags.pop();
        }
        this.mySnippets = '';
        this.ckeditorContent = '';
        this.ckEditor.writeValue('');
        this.cloudContentSuggestionWords = [];
        this.cloudContentSuggestion = [];

        const data = {
            idea: {
                title: null,
                description: null,
                tags: null
            }
        };

        this.IdeaService.savePostIdea(data).subscribe();


        const input = {
            'target': this.constants.POSTIDEAFORMFILL,
            'action': 'keystroke'
        };
        this.setUserLogsKey(input);

        this.checkAutoSave = true;

        // this.router.navigate(['listidea']);
        this.ckeditorContent = '';
        this.mySnippets = '';
        this.myKeyWordList = [];
        this.ideaShowList = [];
        this.myKeyWordTip = '';

    }

    // Fuction call on post idea failed
    private IdeaPostedFail(error) {
        this.checkCount = 0;
        this.submitPostDisable = false;
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }

    // Function for remove tags on copy paste
    public checkTag(event) {

        for (let i = 0; i < this.tags.length; i++) {
            if (/[`~!@#$%^*.<>;':"/[\]|{}()=_+-]/.test(this.tags[i])) {
                this.tags.pop();
            } else if (this.tags[i].length <= 1) {
                this.tags.pop();
            }
        }
    }

    // Function for check tags limit
    private isMaxtagReached(event) {

        for (let i = 0; i < this.tags.length; i++) {
            if (/[`~!@#$%^*.<>;':"/[\]|{}()=_+-]/.test(this.tags[i])) {
                this.tags.pop();
            } else if (this.tags[i].length <= 1) {
                this.tags.pop();
            }
        }

        const size = this.tags.length;

        for (let i = 0; i < size; i++) {
            for (let j = i + 1; j < size; j++) {
                if (this.tags[i] == this.tags[j]) {
                    this.tags.pop();
                }
            }
        }


        if (event.key === 'Control') {

        } else {
            if (this.tags.length > 5) {
                this.tags.pop();
                this.maxTag = true;
            } else {
                this.maxTag = false;
            }
        }
    }

    // Function for user info success for versioning
    public userInfoSuccess(data) {
        console.log('post idea');

        this.userVersion = data.version;

        if (data.version === 'Version_1') {
            // 无任何功能
            this.canSuggest = false;
        } else {
            this.canSuggest = true;
        }


        if (data.version === 'Version_1') {
            this.versioning = false;
            this.keyWordHidden = true;
        } else if (data.version === 'Version_2') {
            this.keyWordShow = true;
            this.sentenceSuggestShow = false;
            this.descriptionShow = true;
            this.versioning = false;
            this.showSuggest = true;
        } else if (data.version === 'Version_3') {
            this.sentenceSuggestShow = false;
            this.keyWordShow = true;
            this.descriptionShow = true;
            this.versioning = false;
            this.showSuggest = true;
        } else if (data.version === 'Version_4') {
            this.sentenceSuggestShow = false;
            this.keyWordShow = true;
            this.descriptionShow = true;
            this.versioning = false;
            this.showSuggest = true;
        } else if (data.version === 'Version_5') {
            this.keyWordHidden = true;
            this.sentenceSuggestShow = true;
            this.keyWordShow = false;
            this.descriptionShow = true;
            this.versioning = false;
        } else if (data.version === 'Version_6') {
            this.keyWordHidden = true;
            this.sentenceSuggestShow = true;
            this.keyWordShow = false;
            this.descriptionShow = true;
            this.versioning = false;
        } else if (data.version === 'Version_7') {
            this.keyWordHidden = true;
            this.sentenceSuggestShow = true;
            this.keyWordShow = false;
            this.descriptionShow = true;
            this.versioning = false;
        } else if (data.version === 'Version_8') {
            this.sentenceSuggestShow = true;
            this.keyWordShow = true;
            this.descriptionShow = true;
            this.versioning = false;
        } else if (data.version === 'Version_9') {
            this.sentenceSuggestShow = true;
            this.keyWordShow = true;
            this.descriptionShow = true;
            this.versioning = false;
        } else if (data.version === 'Version_10') {
            this.sentenceSuggestShow = true;
            this.keyWordShow = true;
            this.descriptionShow = true;
            this.versioning = false;
        }else if (data.version === 'Version_11') {
            this.sentenceSuggestShow = false;
            this.keyWordShow = true;
            this.descriptionShow = true;
            this.versioning = false;
        }else if (data.version === 'Version_12') {
            this.sentenceSuggestShow = true;
            this.keyWordShow = false;
            this.keyWordHidden = true;
            console.log("111")
            this.descriptionShow = false;
            this.versioning = false;
        }else if (data.version === 'Version_13') {
            this.sentenceSuggestShow = true;
            this.keyWordShow = true;
            this.descriptionShow = true;
            this.versioning = false;
        }else if (data.version === 'Version_14') {
            console.log("version 1")
            this.sentenceSuggestShow = false;
            this.keyWordShow = false;
            this.descriptionShow = false;
            this.versioning = false;
            this.showIdeaTopWindow= false;
            this.showIdeaButton = false;
        }
    }

    // Function for user info failed API responce
    public userInfoFail(err) {
    }

    // Function for get unique keyword
    public getUniqueKeywords(keyword) {
        const newKeywords = [];
        for (let i = 0; i < keyword.length; i++) {
            if (JSON.stringify(this.cloudContentSuggestionWords).indexOf(JSON.stringify(keyword[i].content)) < 0) {
                newKeywords.push(keyword[i]);
            }
        }
        return newKeywords;
    }

    /**
     * 判断是否是数字
     */
    public isNumber(value){
        if(isNaN(value)){
            return false;
        }
        else{
            return true;
        }
    }

    // Function call when ckeditor ready
    private onReady($event) {
        var that = this;
        var skips = [37, 38, 39, 40, 16, 17, 18, 19, 20];
        var suggestKeys = [32, 188, 189, 190, 186, 222, 2228273, 2228415];
        this.ckEditor.instance.on('change', (event) => {
            /*var content = this.ckEditor.instance.getSelection().getStartElement().getText()
            const tip = {
                'target': 'user input',
                'value': content,
                'action': "user input",
                'context': that.ckEditor.instance.editable().getText()
            };
            this.setUserLogs(tip);*/


        });
        this.ckEditor.instance.on('key', (event) => {


            if(!this.showIdeaButton){
                return
            }

            const out_input = event.data.domEvent.$.code;
            this.onKeyPressUserForCkeditor(out_input);

            console.log(event.data.keyCode);
            console.log(this.getPrevChar(this.ckEditor.instance));

            if (this.isFirstLoad) {
                this.getTop10Keyword();
                this.getTopIdeas(this.currentIdeasIndex);
                this.isFirstLoad = false;
            }


            // setTimeout(() => {

            if (event.data.keyCode === 8) {
                console.log('backspace');
                const tip = {
                    'target': 'backspace',
                    'value': content,
                    'action': 'backspace',
                    'context': that.ckEditor.instance.editable().getText()
                };
                this.setUserLogs(tip);

                var content = this.ckEditor.instance.editable().getText();
                this.checkKey(content);
            }

            var editor = this.ckEditor.instance;


            if (skips.indexOf(event.data.keyCode) < 0) {
                var sel = editor.getSelection();
                var cursor = sel._.cache.nativeSel.anchorOffset;
                var data = sel._.cache.nativeSel.focusNode.data;
                var currentElement = sel.getStartElement();
                var ranges = sel.getRanges();
                var endParent = ranges[0].endContainer.getParent();
                var startParent = ranges[0].startContainer.getParent();
                if ((currentElement.getAttribute('class') != null && currentElement.getAttribute('class').indexOf('highlight') != -1)
                    || (endParent.getAttribute('class') != null && endParent.getAttribute('class').indexOf('highlight') != -1)) {
                    var className = '';
                    if (currentElement.getAttribute('class') != null) {
                        className = currentElement.getAttribute('class');
                    } else {
                        className = endParent.getAttribute('class');
                    }
                    var style = new CKEDITOR.style({
                        name: 'highlight'
                        , element: 'span'
                        , attributes: {'class': className}
                        , styles: {'color': '#ff0000'}
                    });

                    var clone = ranges[0].clone();
                    if (event.data.keyCode == 8 && cursor == data.length) {
                        currentElement.remove(true);
                        editor.getSelection().getStartElement().$.normalize();
                    } else if (startParent.getAttribute('class') != null && startParent.getAttribute('class').indexOf('highlight') != -1
                        && endParent.getAttribute('class') != null && endParent.getAttribute('class').indexOf('highlight') != -1) {
                        startParent.remove(true);
                        endParent.remove(true);
                        sel.selectRanges([ranges[0]]);
                        setTimeout(function () {
                            editor.getSelection().getStartElement().$.normalize();
                        }, 10);
                    } else if (startParent.getAttribute('class') != null && startParent.getAttribute('class').indexOf('highlight') != -1) {
                        if (ranges[0].endOffset == 1) {
                            ranges[0].setEndAfter(clone.endContainer);
                        }
                        startParent.remove(true);
                        sel.selectRanges([ranges[0]]);
                        editor.getSelection().getStartElement().$.normalize();
                    } else if (endParent.getAttribute('class') != null && endParent.getAttribute('class').indexOf('highlight') != -1) {
                        if (ranges[0].startOffset == 0 && clone.startContainer.getAttribute('class') != null
                            && clone.startContainer.getAttribute('class').indexOf('highlight') != -1) {
                            console.log('0');
                            ranges[0].setStart(clone.endContainer, 0);
                        }
                        endParent.remove(true);
                        sel.selectRanges([ranges[0]]);
                        editor.getSelection().getStartElement().$.normalize();
                    } else {
                        style.remove(editor);
                        setTimeout(function () {
                            editor.getSelection().getStartElement().$.normalize();
                        }, 10);
                    }
                } else if (event.data.keyCode == 8) {
                    setTimeout(function () {
                        editor.getSelection().getStartElement().$.normalize();
                    }, 10);
                }
            }


            if (suggestKeys.indexOf(event.data.keyCode) != -1 && this.canSuggest && !this.processing) {



                // 判断是否在匹配中
                if (this.isSuggesting) {
                    return;
                }

                this.isNeed = true;
                var userInputContent = this.ckEditor.instance.editable().getText();
                var test = '/[,.]/gi';
                userInputContent = userInputContent.replace(eval(test), ' ');
                userInputContent = userInputContent.replace(/\u200b/g, '');

                setTimeout(function () {
                    var sel = editor.getSelection();
                    var cursor = sel._.cache.nativeSel.anchorOffset;
                    var data = sel._.cache.nativeSel.focusNode.data;
                    var node = sel._.cache.nativeSel.focusNode;
                    var element = sel.getStartElement();
                    var range = editor.createRange();
                    var outcome = that.locateKeywords(data, cursor);
                    var key = outcome.keyword;

                    // check当前输入是否是关键词
                    var input = key.trim().split(/[\s\t]+/);
                    var keyword = input[input.length - 1];


                    if(that.isNumber(keyword)) {
                        return
                    }

                    if (outcome.startIndex != -1) {
                        var textNode = that.getTextNodes(element, data, outcome.keyword, outcome.startIndex);
                        range.setStart(textNode, outcome.startIndex);
                        range.setEnd(textNode, outcome.startIndex + outcome.keyword.length);
                        console.log(range);
                        range.optimize();

                        var style = new CKEDITOR.style({
                            name: 'highlight'
                            , element: 'span'
                            , attributes: {'class': that.setClassName(outcome.keyword)}
                            , styles: {'color': '#dddddd'}
                        });
                        style.applyToRange(range);
                        // this.confirmKeyword(editor, outcome.keyword, this.queryKeywordList);
                    }


                    // const firstContent = userInputContent.trim();
                    // var res = firstContent.split(/[\s\t]+/);



                    console.log(keyword.toLowerCase());

                    that.IdeaService.checkKeyWord({'content': keyword.toLowerCase()}).subscribe(
                        data => {
                            console.log(data);

                            const tip = {
                                'target': 'check keyword',
                                'value': keyword,
                                'action': 'suggest',
                                'context': that.ckEditor.instance.editable().getText()
                            };
                            that.setUserLogs(tip);

                            if (data.result) {
                                // 关键词
                                that.myKeyWordTip = 'Matching…';
                                that.isSuggesting = true;


                                var nowLength = that.queryKeywordList.length;
                                if (nowLength >= 3) {

                                    // 当前键入的关键字，是否在关键词列表中，如果在，其位置是否在最后三个词
                                    var position = that.queryKeywordList.indexOf(keyword);

                                    if (position < (nowLength - 3)) {
                                        for (var i = 0; i <= nowLength - 3; i++) {
                                            try {

                                                var nodeList = that.ckEditor.instance.getSelection().document.find('.' + that.queryKeywordList[i]);
                                                for (var j = 0; j < nodeList.count(); j++) {
                                                    var element = new CKEDITOR.dom.element(nodeList.getItem(j).$);
                                                    element.removeStyle('color');
                                                }
                                            }catch (e) {
                                               console.log("error")
                                            }


                                        }
                                    }

                                    if (that.queryKeywordList.indexOf(keyword) < (nowLength - 3)) {
                                        that.queryKeywordList.push(keyword);
                                    }
                                } else {
                                    if (-1 == that.queryKeywordList.indexOf(keyword)) {
                                        that.queryKeywordList.push(keyword);
                                    }
                                }

                                if (that.queryKeywordList.length < 3) {
                                    var keywords = that.queryKeywordList;
                                } else {
                                    var length = that.queryKeywordList.length;
                                    var keywords = that.queryKeywordList.slice(length - 3, length);
                                }
                                that.queryKeywordList = keywords;

                                that.confirmKeyword(editor, outcome.keyword, that.queryKeywordList);

                                that.doSuggest();
                            } else {
                                that.confirmKeyword(editor, outcome.keyword, that.queryKeywordList);
                                return;
                            }
                        },
                        error => that.autoSuggestionFail(error));

                }, 10);


            } else if (this.ckEditor.instance.editable().getText().trim() == '') {
                this.cloudContentSuggestion = [];
                this.cloudContentSuggestionWords = [];
            } else {
                this.isNeed = false;
                console.log(this.isNeed);
                if ((event.data.keyCode == 46) || (event.data.keyCode == 1114198) || (event.data.keyCode == 1114202)
                    || (event.data.keyCode == 1114200)) {
                    // this.putKeywords();
                }
            }
            // }, 10);
        });
    }

    public checkKey(content) {

        var tempSave = [];

        this.queryKeywordList.forEach(function (splitItem, index) {
            if (-1 != content.indexOf(splitItem)) {
                tempSave.push(splitItem);
            }
        });


        this.queryKeywordList = tempSave;

        console.log(this.queryKeywordList.join(' '));

    }

    public doSuggest() {

        console.log('suggest');

        this.isSuccessful = false;

        var queryContent = '';

        if (this.queryKeywordList.length >= 3) {
            queryContent = this.queryKeywordList.slice(this.queryKeywordList.length - 3).join(' ');
            console.log(queryContent);
        } else {
            queryContent = this.queryKeywordList.join(' ');
        }


        const cloudData = {
            content: queryContent.toLowerCase(),
            wholeContent: queryContent.toLowerCase()
        };

        this.IdeaService.getReproducibleCitableKeywordsSuggestion(cloudData).subscribe(
            data => this.autoSuggestionSucces(queryContent, cloudData.wholeContent, data),
            error => this.autoSuggestionFail(error));
    }


    public autoSuggestionSucces(queryContent, wholeContent, result, needContinue = true, currentIndex = 3) {

        /*if(!needContinue){
            return
        }*/

        this.isSuccessful = true;
        this.currentIndex = 0;


        this.cloudContentSuggestionWords = result.sentence;

        var that = this;

        if (result.autoComplete.length == 0) {

            this.myKeyWordTip = 'No matching';
            this.cloudContentSuggestionWords = [];
            this.cloudContentSuggestion = [];
            this.isSuggesting = false;

        } else {
            this.myKeyWordTip = 'Successful match';


            if (this.sentenceSuggestShow) {

                this.myKeyWordList = this.queryKeywordList;

                if (this.myKeyWordList.length > 3) {
                    var length = this.myKeyWordList.length;
                    this.myKeyWordList = this.myKeyWordList.slice(length - 3, length);
                }

            }

            if (this.sentenceSuggestShow) {


                this.autoCompleteList = result.autoComplete;
                this.autoKeywordList = result.keyWordList;
                var tempResult = [];

                $.each(this.autoCompleteList, function (index, item) {

                    // var temp = queryContent.trim().split(" ")
                    var temp = result.keyWordList;
                    temp.forEach(function (splitItem, index) {
                        var reg = '/\\b' + splitItem + '\\b/gi';
                        item.content = item.content.replace(eval(reg), '<span>' + splitItem + '</span>');
                    });

                });


                if (this.autoCompleteList.length > 10) {
                    this.pageButtonShow = true;
                    this.currentIndex = 10;
                    tempResult = result.autoComplete.slice(0, 10);
                } else {
                    this.pageButtonShow = false;
                    tempResult = result.autoComplete;
                }


                var contextData = {
                    'currentText': that.ckEditor.instance.editable().getText(),
                    'suggestions': result.autoComplete,
                    'keyword': this.cloudContentSuggestionWords,
                    'version': this.userVersion
                };

                const tip = {
                    'target': 'match successful',
                    'value': tempResult,
                    'action': 'match successful',
                    'context': JSON.stringify(contextData)
                };
                that.setUserLogs(tip);

                this.cloudContentSuggestion = tempResult;
            }
            this.isSuggesting = false;
            // this.cloudContentSuggestionWords = this.getUniqueKeywords(result.sentence);

        }
    }

    private loadMoreIdeas() {


        this.cloudContentSuggestion = this.cloudContentSuggestion.concat(this.autoCompleteList.slice(this.currentIndex, this.currentIndex + 10));

        this.currentIndex = this.currentIndex + 10;

        if (this.currentIndex + 10 > 30) {
            this.pageButtonShow = false;
            return;
            // this.getMoreIdeasByPage(this.currentIdeasIndex);
        }

    }

    /*  private getMoreIdeas() {

          this.currentIdeasIndex = this.currentIdeasIndex + 1;

          // if(this.currentIdeasIndex * 10 + 10 > this.autoCompleteIdeasList.length) {
          this.getTopIdeas(this.currentIdeasIndex);
      }*/


    private loadMoreConstIdeas() {

        // this.constContentSuggestion = this.constContentSuggestion.concat(this.autoCompleteIdeasList.slice(this.currentIdeasIndex * 10, this.currentIdeasIndex*10 + 10))

        this.currentIdeasIndex = this.currentIdeasIndex + 1;

        // if(this.currentIdeasIndex * 10 + 10 > this.autoCompleteIdeasList.length) {
        this.getTopIdeas(this.currentIdeasIndex);

        // this.pageIdeasButtonShow = false;
        // }

    }


    // Function for auto suggestion failed
    private autoSuggestionFail(error) {
        this.isSuggesting = false;
    }

    // Function for get keyword from API for fill
    public fillKeywords(title, description) {
        const cloudData = {
            content: this.ckEditor.instance.editable().getText(),
            wholeContent: this.ckEditor.instance.editable().getText()
        };

        const data = {
            'autoComplete': [],
            'sentence': [],
            'showCount': 0
        };

        this.fillKeywordsSuccess(data, title, description);
        this.init();

        /*this.IdeaService.getReproducibleCitableKeywordsSuggestion(cloudData).subscribe(
            data => this.fillKeywordsSuccess(data, title, description),
            error => this.autoSuggestionFail(error));*/
    }

    // Function for filled keyword
    private fillKeywordsSuccess(result, title, description) {

        if (title && description) {

            if (title.length >= 2 && description.length >= 3) {
                this.checkCount = this.checkCount + 1;
                if (this.checkCount === 1) {
                    if (result.showCount > 0) {
                        this.citation.count = result.showCount;
                        this.citation.name = result.sentence[0].name;
                        this.citation.date = result.sentence[0].updatedAt;
                    }
                    this.submitPostDisable = true;
                    this.spinner.showProgress();
                    this.onSubmit(title, description);
                }
            } else {
                if (title.length < 2) {
                    toastr.error(this.constants.POSTTITLE);
                }
                if (description.length < 2) {
                    toastr.error(this.constants.POSTDESCRIPTION);
                }
            }
        } else {
            toastr.error(this.constants.ENTERALLFIELD);
        }


    }

    // Function for put keyword using API call
    private putKeywords() {
        setTimeout(() => {
            const cloudData = {
                content: '',
                wholeContent: this.ckEditor.instance.editable().getText()
            };
            this.IdeaService.getReproducibleCitableKeywordsSuggestion(cloudData).subscribe(
                data => this.putKeywordsSuccess(data),
                error => this.autoSuggestionFail(error));
        }, 200);
    }

    // Function after put keyword success
    public putKeywordsSuccess(result) {
        this.cloudContentSuggestionWords = this.getUniqueKeywords(result.sentence);
        this.cloudContentSuggestion = [];
    }

    // Function for put suggestions for ckeditor
    private putSuggestion(suggest) {
        let ckeditorLength = this.ckeditorContent.length;
        let chkStr = '';
        const currentSentence = this.ckEditor.instance.editable().getText().split(/[?!.]/g);
        let curPos = 0;
        const extractStr = currentSentence[currentSentence.length - 1];

        while (chkStr.trim().toLocaleLowerCase() !== extractStr.trim().toLocaleLowerCase() && ckeditorLength >= 0) {

            curPos = ckeditorLength - extractStr.length - 1;
            chkStr = this.ckeditorContent.substring(curPos, curPos + extractStr.length);
            --ckeditorLength;
        }

        // todo 不覆盖已有内容
        // var tempData = this.ckEditor.instance.editable().getText()
        // newContent = this.previousContent + suggest;
        // newContent = tempData + suggest;


        var handleContent = this.replaceKeyword(suggest, this.myKeyWordList);

        // this.ckEditor.instance.editable().appendHtml("<br>");
        this.ckEditor.instance.editable().appendHtml(handleContent);

        // this.ckeditorContent = this.ckEditor.instance.editable().getText();

        // this.cloudContentSuggestion = [];
        // this.putKeywords();
    }


    private putConstSuggestion(suggest) {

        return;

        /*let ckeditorLength = this.ckeditorContent.length;
        let chkStr = '';
        const currentSentence = this.ckEditor.instance.editable().getText().split(/[?!.]/g);
        let curPos = 0;
        const extractStr = currentSentence[currentSentence.length - 1];

        while (chkStr.trim().toLocaleLowerCase() !== extractStr.trim().toLocaleLowerCase() && ckeditorLength >= 0) {

            curPos = ckeditorLength - extractStr.length - 1;
            chkStr = this.ckeditorContent.substring(curPos, curPos + extractStr.length);
            --ckeditorLength;
        }


        // this.ckEditor.instance.editable().appendHtml("<br>");
        this.ckEditor.instance.editable().appendHtml(suggest);*/
    }

    // Function pass tree data
    public getTreeStructure(citedWords) {
        this.getTreeData(citedWords);
    }

    // function for get tree data from API
    private getTreeData(data): void {
        const inputData = {content: [data]};
        this.spinner.showProgress();
        this.IdeaService.getCitationTreeData(inputData).subscribe(
            data => this.generateTree(data),
            error => {
            });
    }

    // function for generate citation tree
    private generateTree(data) {
        this.citationTreeModal.open();
        setTimeout(() => {
            const chartConfig = {
                chart: {
                    container: '#tree-simple',
                    scrollbar: 'fancy',
                    siblingSeparation: 20,
                    subTeeSeparation: 60,
                    connectors: {
                        type: 'step'
                    },
                    node: {
                        HTMLclass: 'nodeExample1'
                    }
                },
                nodeStructure: data

            };
            const chart = new Treant(chartConfig);
        }, 1000);
        this.spinner.hideProgress();

    }

    // Function save data after 2 min
    public savePostIdeaContent() {
        if (this.ckEditor.instance !== null) {
            this.postTitle = this.mySnippets;
            const a = this.ckEditor.instance.editable().getText();
            this.postDescription = a;
            this.postTag = this.tags;
            if (this.postTitle !== undefined || this.postDescription.length > 1) {
                const data = {
                    idea: {
                        title: this.postTitle,
                        description: this.postDescription,
                        tags: this.tags
                    }
                };
                this.IdeaService.savePostIdea(data).subscribe();
            }
        }
    }

    // To call this function when leave from this controller
    ngOnDestroy() {
        // To stop count function call
        this.stopCount();

        // API call for tract navigation sequence
        const seq = {
            sequence: {
                'pageName': 'postIdea',
                'timeSpent': this.start
            }

        };
        this.userService.setUrlSeq(seq).subscribe();


        this.postTitle = this.mySnippets;
        const y = this.ckEditor.instance.editable().getText();
        this.postDescription = y;
        if (!this.checkAutoSave) {

            if (this.mySnippets !== null || this.postDescription.length > 1) {
                const input = confirm(this.constants.SAVEALERT);
                if (input === true) {

                    const data = {
                        idea: {
                            title: this.postTitle,
                            description: this.postDescription,
                            tags: this.tags
                        }
                    };

                    this.IdeaService.savePostIdea(data).subscribe(
                        data => toastr.success(this.constants.IDEASAVE),
                        error => console.log(''));

                } else {
                    const data = {
                        idea: {
                            title: null,
                            description: null,
                            tags: null
                        }
                    };

                    this.IdeaService.savePostIdea(data).subscribe();
                }
            }
        }

    }

    // Function for set user log on Key
    public setUserLogsKey(input) {
        this.userService.setUserLogs(input).subscribe();
    }

    // Function for save post an IDEA
    public savePostIdea(title, description) {

        var that = this;

        if (title !== undefined || description !== undefined) {

            this.postTitle = title;
            this.postDescription = description;

            const data = {
                idea: {
                    title: this.postTitle,
                    description: this.postDescription,
                    tags: this.tags
                }
            };
            this.checkAutoSave = true;
            this.IdeaService.savePostIdea(data).subscribe(
                data => {
                    toastr.success('Idea Saved Successfully');
                },
                error => console.log(''));
        }
    }

    // timer function start count of timeline
    public timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount();
        }, 1);
    }

    // To function for start timstamp count
    public startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    public stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // Function call after view for log API
    ngAfterViewChecked() {
        const self = this;
        $('#postIdeaLog').unbind().mousedown(function (event) {
            self.checkAllLogs(event);
        });
    }

    // Function for check all logs
    public checkAllLogs(event) {
        const self = this;
        let buttons;
        if (event.button === 0) {
            buttons = 'left click';
        } else if (event.button === 1) {
            buttons = 'roller click';
        } else {
            buttons = 'right click';
        }
        const domTarget = event.target;
        const domTargetString = domTarget.toString();
        const stringDemo = domTargetString.substr(12, 25);
        const index = stringDemo.indexOf('E');
        const dom = stringDemo.substr(0, index);
        const text = $(event.target).unbind().text();


        const input = {
            'target': dom + ' ' + text,
            'value': text,
            'action': buttons
        };

        if (input.target.includes('Button')) {

            const input = {
                'target': 'Save post an idea Successfully',
                'value': text,
                'action': buttons
            };
            self.setUserLogs(input);
        } else if (input.target.includes('Input')) {

            const input = {
                'target': 'Save post an idea Successfully',
                'value': text,
                'action': buttons
            };
        } else {
            self.setUserLogs(input);
        }
    }

    // Function for call API for log
    public setUserLogs(input) {
        this.userService.setUserLogs(input).subscribe();
    }

    //Get List of All Tags
    getTags() {
        const input = {
            tags: ''
        };
        this.IdeaService.searchTags(input).subscribe(
            data => this.tagsSerchSuccess(data[0]),
            error => {
            }
        );
    }

    // Successfully found tags and pass to view
    tagsSerchSuccess(result) {
        this.allTags = result.tags;
    }

    // User log for keystroke event for title
    public onKeyPressUser(event) {

        const input = {
            'target': 'HTMLInputElement : ' + event.code + '  Post an idea title',
            'action': 'keystroke',
            'context': this.ckEditor.instance.editable().getText()
        };
        // API call for send user log data
        this.userService.setUserLogs(input).subscribe();
    }

    // User log for keystroke event for title
    public onKeyPressUserForCkeditor(event) {

        const input = {
            'target': 'HTMLInputElement : ' + event + '  Post an idea description',
            'action': 'keystroke',
            'context': this.ckEditor.instance.editable().getText()
        };
        // API call for send user log data
        this.userService.setUserLogs(input).subscribe();
    }


    public onAddingEvent(tagModel): Observable<TagModel> {

        var tag = tagModel.display || tagModel;


        const queryData = {
            'words': tag
        };

        $.ajax({
            type: 'POST',
            dataType: 'json',
            async: false,
            url: 'http://localhost:3001/v1/keywords/findKeywordsByPercent',
            headers: {
                'Content-Type': 'application/json',
                'token': window.localStorage.getItem('crowdsourcing_authToken')
            },
            data: JSON.stringify(queryData),
            success: function (res) {
                if (res.data.count > 0) {
                    if (res.data.percent > 0) {
                        tag = tag + '(' + res.data.count + ':' + res.data.percent + '%)';
                    } else {

                        tag = tag + '(' + res.data.count + ')';
                    }

                    return Observable
                        .of(tag);
                }
            }
        });
        return Observable
            .of(tag);


        /* that.IdeaService.findKeywordsByPercent(queryData).subscribe(
             data => {
               console.log(data)
             },
             error => console.log('error'));*/


    }

    private replaceKeyword(sentence, list) {
        list = list.map(function (item) {
            return '(\\b' + item + '\\b)';
        }).join('|');

        var regex = new RegExp(list, 'gi');
        console.log(regex);

        var output = sentence.replace(regex, function (sMatch) {
            return '<span style="color:#FF0000" class="highlight ' + sMatch + '">' + sMatch + '</span>';
        });
        return output;
    }

    private getPrevChar(editor) {
        var range = editor.getSelection().getRanges()[0],
            startNode = range.startContainer;

        if (startNode.type == CKEDITOR.NODE_TEXT && range.startOffset)
        // Range at the non-zero position of a text node.
            return startNode.getText()[range.startOffset - 1];
        else {
            // Expand the range to the beginning of editable.
            range.collapse(true);
            range.setStartAt(editor.editable(), CKEDITOR.POSITION_AFTER_START);

            // Let's use the walker to find the closes (previous) text node.
            var walker = new CKEDITOR.dom.walker(range),
                node;

            while ((node = walker.previous())) {
                // If found, return the last character of the text node.
                if (node.type == CKEDITOR.NODE_TEXT)
                    return node.getText().slice(-1);
            }
        }

        // Selection starts at the 0 index of the text node and/or there's no previous text node in contents.
        return null;
    }

    private getTextNodes(element, data, key, startIndex) {
        var children = element.getChildren();
        var child, results;
        var regex = RegExp('\\b' + key + '\\b', 'g');
        for (var i = children.count(); i--;) {
            child = children.getItem(i);

            if (child.type == CKEDITOR.NODE_ELEMENT)
                this.getTextNodes(child, data, key, startIndex);
            else if (child.type == CKEDITOR.NODE_TEXT) {
                while ((results = regex.exec(child.$.data)) !== null) {
                    if (child.$.data == data && regex.lastIndex == startIndex + key.length) {
                        var text = child;
                        return child;
                    }
                }
            }
        }
    }

    /*private locateKeywords(data, cursor, keywords) {
        var results;
        for (var i = 0; i < keywords.length; i++) {
            var regex = RegExp('\\b' + keywords[i] + '\\b', 'g');
            while ((results = regex.exec(data)) !== null) {
                console.log(`Found ${results[0]}. Next starts at ${regex.lastIndex}.`);
                if (regex.lastIndex + 1 == cursor) {
                    return {keyword: results[0], startIndex: regex.lastIndex - results[0].length};
                }
            }
        }
        return {keyword: '', startIndex: -1};
    }*/

    private locateKeywords(data, cursor) {
        var results;
        var regex = RegExp('\\b\\w+\\b', 'g');
        while ((results = regex.exec(data)) !== null) {
            console.log(`Found ${results[0]}. Next starts at ${regex.lastIndex}.`);
            if (regex.lastIndex + 1 == cursor) {
                return {keyword: results[0], startIndex: regex.lastIndex - results[0].length};
            }
        }
        return {keyword: '', startIndex: -1};
    }


    private confirmKeyword(editor, keyword, keywords = []) {
        // var keywords = ['test', 'this', 'system'];
        var that = this;
        var children = editor.document.find('.' + that.setClassName(keyword));
        if (keywords.indexOf(keyword) != -1) {
            for (var i = 0; i < children.count(); i++) {
                var child = children.getItem(i);
                child.setAttribute('class', that.setClassName(keyword) + ' highlight');
                child.setAttribute('style', 'color: #ff0000;');
            }
        } else {
            for (var i = 0; i < children.count(); i++) {
                var child = children.getItem(i);
                child.remove(true);
            }
        }
        editor.getSelection().getStartElement().$.normalize();
    }

    private setClassName(keyword) {
        var invalidClass = /^[0-9].*$/;
        if (invalidClass.test(keyword) == true) {
            return 'n' + keyword;
        } else {
            return keyword;
        }
    }

    private titleClickHandler(title) {
        console.log('click');
        this.titleClick = true;
        this.mySnippets = title;
        this.autoScrollFilter = true;
    }

    private titleInputFouceOut() {
        console.log('fouce');
        var that = this;
        setTimeout(function () {
            if (!this.titleClick) {
                that.autoScrollFilter = true;
            }
        }, 1000);
    }


}
